package cn.tedu.boot02_2.controller;

import cn.tedu.boot02_2.entity.Product_2;
import cn.tedu.boot02_2.utils.DBUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

@RestController
public class Product_2Controller {
    @RequestMapping("insert")
    public String insert(Product_2 product_2) {
        System.out.println("product_2 = " + product_2);
        try(Connection connection = DBUtil.getConnection()) {
            String sql = "INSERT INTO product_2 VALUES(NULL, ?, ?, ?)";
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setString(1, product_2.getTitle());
            ps.setDouble(2, product_2.getPrice());
            ps.setInt(3, product_2.getNum());
            ps.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return "添加完成!";
    }
    @RequestMapping("/select")
    public String select() {
        ArrayList<Product_2> list = new ArrayList<>();
        try(Connection connection = DBUtil.getConnection();) {
            String sql = "SELECT * FROM product_2";
            PreparedStatement ps = connection.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();
            while(rs.next()) {
                Product_2 product_2 = new Product_2();
                product_2.setId(rs.getInt("id"));
                product_2.setTitle(rs.getString("title"));
                product_2.setPrice(rs.getDouble("price"));
                product_2.setNum(rs.getInt("num"));
                list.add(product_2);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return list.toString();
    }

}
